<template>
    <span>{{timeSlot}}</span>
</template>

<script>
    const SEC = 1000;
    const MINUTE = SEC * 60;
    const HOUR = MINUTE * 60;
    const DAY = HOUR * 24;
    const WEEK = 7 * DAY;
    const MONTH = 30 * DAY;
    const YEAR = 365 * DAY;
    const timeUnit = [
        {label: "秒", value: SEC},
        {label: "分钟", value: MINUTE},
        {label: "小时", value: HOUR},
        {label: "天", value: DAY},
        {label: "周", value: WEEK},
        {label: "个月", value: MONTH},
        {label: "年", value: YEAR},
    ];

    /**
     * @param timeSlot!:int 应当为一个整数，描述一个时间长度，单位为ms
     * @param tolerateUnit?:int 应当为一个整数，描述能够容忍的时间精度。如: <br>
     *     当 tolerateUnit===1, 40*DAY -> 1个月
     *     当 tolerateUnit===2, 40*DAY -> 1个月 1周
     *     当 tolerateUnit===3, 40*DAY -> 1个月 1周 3天
     *     当 tolerateUnit===4, 40*DAY -> 1个月 1周 3天
     * @param split?:string 两个时间单位之间的分割符：1个月[split]1天
     * @param numProcessor?:(v!:int)=>string|int 处理数字，可以实现如：25天->二十五天
     */
    function timeSlot2String(timeSlot,tolerateUnit=2,split="",numProcessor=v=>v) {
        if(tolerateUnit <= 0) return "";
        let i = timeUnit.length - 1;
        while(i>=0 && timeUnit[i].value>timeSlot) i -= 1;
        if(i<=0) return numProcessor(Math.round(timeSlot/timeUnit[0].value))+timeUnit[0].label;
        if(tolerateUnit === 1) return numProcessor(Math.round(timeSlot/timeUnit[i].value))+timeUnit[i].label;
        let disparity = timeSlot;
        const ansSet = [];
        for(;i>0;i-=1){
            const quotient = Math.floor(timeSlot/timeUnit[i].value);
            const remainder = timeSlot % timeUnit[i].value;
            const tempDisparity = remainder%timeUnit[i-1].value;
            if(disparity<tempDisparity) continue;
            const nextUnit = remainder < timeUnit[0].value/2 ? "" :
                split+timeSlot2String(remainder,tolerateUnit-1,split,numProcessor);
            ansSet.push(numProcessor(quotient)+timeUnit[i].label + nextUnit);
        }
        let finalAns = ansSet[0];
        ansSet.forEach(v=>{
            if(v.length<finalAns.length) finalAns = v;
        });
        return finalAns;
    }

    /**
     * 提供时间段数值转字符串服务。
     * 输入精确到毫秒的value，将转为一个描述此时间段的字符串。
     * 如：<br>
     *     3024000000 -> '35天'
     */
    export default {
        name: "TimeSlot",
        props:{
            value:{
                require:true,
                type: Number,
            },
            tolerateUnit:{
                type: Number,
                default: 2
            },
        },
        computed:{
            timeSlot(){
                return timeSlot2String(this.value,this.tolerateUnit);
            }
        }
    }
</script>

<style scoped>

</style>